package com.qd.common.sys.util;

import com.blueconic.browscap.Capabilities;
import com.blueconic.browscap.ParseException;
import com.blueconic.browscap.UserAgentParser;
import com.blueconic.browscap.UserAgentService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 浏览器用户代理解析
 *
 * @author sjk
 */
@Slf4j
public class UserAgent {
    /**
     * 浏览器
     */
    private String browser = "";

    /**
     * 操作系统
     */
    private String operatingSystem = "";

    /**
     * 解析器
     */
    private static UserAgentParser parser = null;

    static {
        try {
            long start = System.currentTimeMillis();
            try{
                parser = new UserAgentService().loadParser();
            }finally {
                long end = System.currentTimeMillis();
                log.info("耗时: {}s",(end-start)/1000);
            }

        } catch (IOException | ParseException e) {
            log.error("获取用户代理异常", e);
        }
    }

    public UserAgent(String userAgentString) {
        if (parser != null) {
            String userAgentLowercaseString = userAgentString == null ? null : userAgentString.toLowerCase();
            Capabilities capabilities = parser.parse(userAgentLowercaseString);
            this.browser = String.format("%s %s", capabilities.getBrowser(), capabilities.getBrowserMajorVersion());
            this.operatingSystem = capabilities.getPlatform();
        }
    }

    public static UserAgent parseUserAgentString(String userAgentString) {
        return new UserAgent(userAgentString);
    }

    public static void init() {
        //什么事情都不做，只是为了初始化static代码块
    }

    public String getBrowser() {
        return browser;
    }

    public String getOperatingSystem() {
        return operatingSystem;
    }
}